package io.gitee.yxsnake.framework.web.core;

import io.gitee.yxsnake.framework.core.domain.Result;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

/**
 * @author snake
 * @description
 * @since 2024/11/2 22:04
 */
@Component
@SuppressWarnings("ALL")
public class BaseController {

    @Autowired
    protected HttpServletRequest request;

    @Autowired
    protected HttpServletResponse response;

    /**
     * 成功返回
     *
     * @param object 返回对象
     * @param <T>    T
     * @return ResponseEntity
     */
    protected <T> ResponseEntity<Result<T>> success(T object) {
        return success(object, null, HttpStatus.OK);
    }

    /**
     * 成功返回
     *
     * @return ResponseEntity
     */
    protected ResponseEntity success() {
        return success(HttpStatus.OK);
    }

    /**
     * 成功返回
     *
     * @param status HttpStatus对象
     * @param <T>    T
     * @return ResponseEntity
     */
    protected <T> ResponseEntity<Result<T>> success(HttpStatus status) {
        return success(null, null, status);
    }

    /**
     * 成功返回
     *
     * @param object  返回对象
     * @param headers HttpHeaders对象
     * @param status  HttpStatus对象
     * @param <T>     T
     * @return ResponseEntity
     */
    protected <T> ResponseEntity<Result<T>> success(T object, HttpHeaders headers, HttpStatus status) {
        if (headers == null) {
            headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
        }
        return new ResponseEntity<>(
                Result.<T>builder()
                        .data(object)
                        .code(io.gitee.yxsnake.framework.core.constant.HttpStatus.SUCCESS)
                        .msg("操作成功")
                        .build(), headers, status);
    }

    @SuppressWarnings("unchecked")
    protected <T> ResponseEntity directlyReturn(T object) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        return new ResponseEntity(object, headers, HttpStatus.OK);
    }

    protected <T> ResponseEntity<Result<T>> fail(Result<T> result) {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        return new ResponseEntity<>(result, httpHeaders, HttpStatus.INTERNAL_SERVER_ERROR);
    }

    protected Result<Void> toAjax(int rows) {
        return rows > 0 ? Result.ok() : Result.fail();
    }

    /**
     * 响应返回结果
     *
     * @param result 结果
     * @return 操作结果
     */
    protected Result<Void> toAjax(boolean result) {
        return result ? Result.ok() : Result.fail();
    }
}
